<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.company')" prop="companyId">
            <el-select v-model="formData.companyId" :placeholder="t('common.inputText') + t('su.invoice.company')" @change="chooseCompany">
              <el-option
                v-for="dict in companyList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.bank')" prop="companyBankId">
            <el-select v-model="formData.companyBankId" :placeholder="t('common.inputText') + t('su.invoice.bank')">
              <el-option
                v-for="dict in companyBanks"
                :key="dict.id"
                :label="dict.bankName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.no')" prop="no">
            <el-input v-model="formData.no" :placeholder="t('common.inputText') + t('su.invoice.no')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.kind')" prop="kind">
            <el-select v-model="formData.kind" :placeholder="t('common.inputText') + t('su.invoice.kind')">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SU_INVOICE_KIND)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.invoiceDate')" prop="invoiceDate">
            <el-date-picker
              v-model="formData.invoiceDate"
              type="date"
              value-format="x"
              :placeholder="t('common.inputText') + t('su.invoice.invoiceDate')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.dueDate')" prop="dueDate">
            <el-date-picker
              v-model="formData.dueDate"
              type="date"
              value-format="x"
              :placeholder="t('common.inputText') + t('su.invoice.dueDate')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.customer')" prop="customerId">
            <el-select
              v-model="formData.customerId"
              :placeholder="t('common.inputText') + t('su.invoice.customer')"
              clearable
              filterable
              class="!w-240px"
            >
              <el-option
                v-for="customer in customerList"
                :key="customer.id"
                :label="customer.name"
                :value="customer.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.brand')" prop="brandId">
            <el-select
              v-model="formData.brandId"
              :placeholder="t('common.inputText') + t('su.invoice.brand')"
              clearable
              filterable
              class="!w-240px"
            >
              <el-option
                v-for="brand in brandList"
                :key="brand.id"
                :label="brand.name"
                :value="brand.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.exchange')" prop="exchange">
            <el-input v-model="formData.exchange" :placeholder="t('common.inputText') + t('su.invoice.exchange')"/>
          </el-form-item>
        </el-col>
        <el-col v-if="formData.kind == 'Factory'" :span="12">
          <el-form-item :label="t('su.invoice.tax')" prop="tax">
            <el-input v-model="formData.tax" :placeholder="t('common.inputText') + t('su.invoice.tax')"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('su.invoice.productInfo')" prop="productItems">
            <el-table :data="productItems" :stripe="true" :show-overflow-tooltip="true">
              <el-table-column :label="t('su.invoice.product')" min-width="120px">
                <template #default="scope">
                  <el-form-item :prop="'list.' + scope.$index + '.productId'" :rules="formRules.productId">
                    <el-select
                      v-model="scope.row.productId"
                      :placeholder="t('common.inputText') + t('su.invoice.product')"
                      clearable
                      filterable
                      class="!w-240px"
                      @change="changeProduct(scope.row)"
                    >
                      <el-option
                        v-for="product in productList"
                        :key="product.id"
                        :label="product.code"
                        :value="product.id"
                      />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="t('su.invoice.sku')" min-width="120px">
                <template #default="scope">
                  <el-form-item :prop="'list.' + scope.$index + '.skuId'" :rules="formRules.skuId">
                  <el-select
                    v-model="scope.row.skuId"
                    :placeholder="t('common.inputText') + t('su.invoice.sku')"
                    clearable
                    filterable
                    class="!w-240px"
                    @change="changeSku(scope.row)"
                  >
                    <el-option
                      v-for="product in scope.row.skuInfos"
                      :key="product.id"
                      :label="product.propertyInfo"
                      :value="product.id"
                    />
                  </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="formData.kind != 'Factory' ? (t('su.invoice.sale') + '$') : (t('su.invoice.sale') + '¥')" min-width="120px">
                <template #default="scope">
                  <el-form-item v-if="formData.kind != 'Factory'" :prop="'list.' + scope.$index + '.productSaleUs'" :rules="formRules.productSaleUs">
                  <el-input v-model="scope.row.productSaleUs"/>
                  </el-form-item>
                  <el-form-item v-if="formData.kind == 'Factory'" :prop="'list.' + scope.$index + '.productSaleRmb'" :rules="formRules.productSaleRmb">
                    <el-input v-model="scope.row.productSaleRmb"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="formData.kind != 'Factory' ? (t('su.invoice.purhase') + '$') : (t('su.invoice.purhase') + '¥')" min-width="120px">
                <template #default="scope">
                  <el-form-item v-if="formData.kind != 'Factory'" :prop="'list.' + scope.$index + '.productPurhaseUs'" :rules="formRules.productPurhaseUs">
                  <el-input v-model="scope.row.productPurhaseUs"/>
                  </el-form-item>
                  <el-form-item v-if="formData.kind == 'Factory'" :prop="'list.' + scope.$index + '.productPurhaseRmb'" :rules="formRules.productPurhaseRmb">
                    <el-input v-model="scope.row.productPurhaseRmb"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="t('su.invoice.count')" min-width="120px">
                <template #default="scope">
                  <el-form-item :prop="'list.' + scope.$index + '.count'" :rules="formRules.count">
                  <el-input-number v-model="scope.row.count"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="t('form.operate')" align="center" fixed="right">
                <template #default="scope">
                  <el-button
                    link
                    type="danger"
                    @click="handleDelete(scope.$index)"
                  >
                    {{ t('action.del') }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              type="primary"
              style="width: 100%"
              plain
              @click="addProduct"
            >
              <Icon icon="ep:plus" class="mr-5px"/>
              {{ t('action.add') }}
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('su.invoice.otherInfo')" prop="otherItems">
            <el-table :data="otherItems" :stripe="true" :show-overflow-tooltip="true">
              <el-table-column :label="t('su.invoice.itemName')" min-width="120px">
                <template #default="scope">
                  <el-form-item :prop="'list.' + scope.$index + '.itemName'" :rules="formRules.itemName">
                    <el-input v-model="scope.row.itemName"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="formData.kind != 'Factory' ? (t('su.invoice.sale') + '$') : (t('su.invoice.sale') + '¥')" min-width="120px">
                <template #default="scope">
                  <el-form-item v-if="formData.kind != 'Factory'" :prop="'list.' + scope.$index + '.totalSaleUs'" :rules="formRules.totalSaleUs">
                    <el-input v-model="scope.row.totalSaleUs"/>
                  </el-form-item>
                  <el-form-item v-if="formData.kind == 'Factory'" :prop="'list.' + scope.$index + '.totalSaleRmb'" :rules="formRules.totalSaleRmb">
                    <el-input v-model="scope.row.totalSaleRmb"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="formData.kind != 'Factory' ? (t('su.invoice.purhase') + '$') : (t('su.invoice.purhase') + '¥')" min-width="120px">
                <template #default="scope">
                  <el-form-item v-if="formData.kind != 'Factory'" :prop="'list.' + scope.$index + '.totalPurhaseUs'" :rules="formRules.totalPurhaseUs">
                    <el-input v-model="scope.row.totalPurhaseUs"/>
                  </el-form-item>
                  <el-form-item v-if="formData.kind == 'Factory'" :prop="'list.' + scope.$index + '.totalPurhaseRmb'" :rules="formRules.totalPurhaseRmb">
                    <el-input v-model="scope.row.totalPurhaseRmb"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="t('su.invoice.description')" min-width="120px">
                <template #default="scope">
                  <el-form-item :prop="'list.' + scope.$index + '.description'" >
                    <el-input v-model="scope.row.description"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column :label="t('form.operate')" align="center" fixed="right">
                <template #default="scope">
                  <el-button
                    link
                    type="danger"
                    @click="handleDeleteOther(scope.$index)"
                  >
                    {{ t('action.del') }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              type="primary"
              style="width: 100%"
              plain
              @click="addOther"
            >
              <Icon icon="ep:plus" class="mr-5px"/>
              {{ t('action.add') }}
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('su.invoice.shipTo')" prop="shipTo">
            <el-input :rows="3"
                      type="textarea" v-model="formData.shipTo" :placeholder="t('common.inputText') + t('su.invoice.shipTo')"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('su.invoice.notes')" prop="notes">
            <el-input v-model="formData.notes" :placeholder="t('common.inputText') + t('su.invoice.notes')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.supplier')" prop="supplierId">
            <el-select v-model="formData.supplierId" :placeholder="t('common.inputText') + t('su.invoice.supplier')" @change="chooseSupplier">
              <el-option
                v-for="dict in supplierList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.supplierBank')" prop="supplierBankId">
            <el-select v-model="formData.supplierBankId" :placeholder="t('common.inputText') + t('su.invoice.supplierBank')">
              <el-option
                v-for="dict in supplierBanks"
                :key="dict.id"
                :label="dict.bankName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.supplerManager')" prop="supplerManager">
            <el-input v-model="formData.supplerManager" :placeholder="t('common.inputText') + t('su.invoice.supplerManager')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.buyer')" prop="buyer">
            <el-input v-model="formData.buyer" :placeholder="t('common.inputText') + t('su.invoice.buyer')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.po')" prop="po">
            <el-input v-model="formData.po" :placeholder="t('common.inputText') + t('su.invoice.po')"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="t('su.invoice.payAction')" prop="payAction">
            <el-select v-model="formData.payAction" :placeholder="t('common.inputText') + t('su.invoice.payAction')">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SU_INVOICD_PAY_ACTION)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.saler')" prop="term">
            <el-input v-model="formData.term" :placeholder="t('common.inputText') + t('su.invoice.saler')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('su.invoice.bill')" prop="bill">
            <el-input v-model="formData.bill" :placeholder="t('common.inputText') + t('su.invoice.bill')"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('su.invoice.remarks')" prop="remarks">
            <el-input v-model="formData.remarks" :placeholder="t('common.inputText') + t('su.invoice.remarks')"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('common.ok') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {getStrDictOptions, DICT_TYPE} from '@/utils/dict'
import {ProformaInvoiceApi, ProformaInvoiceVO} from '@/api/su/pi'
import {CommonApi} from "@/api/su/common";
import {array} from "vue-types";

/** 形式发票 表单 */
defineOptions({name: 'ProformaInvoiceForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  no: undefined,
  invoiceDate: undefined,
  dueDate: undefined,
  kind: undefined,
  customerId: undefined,
  brandId: undefined,
  companyId: undefined,
  companyBankId: undefined,
  supplierId: undefined,
  supplierBankId: undefined,
  buyer: undefined,
  supplerManager: undefined,
  shipTo: undefined,
  po: undefined,
  notes: undefined,
  payAction: undefined,
  term: undefined,
  bill: undefined,
  remarks: undefined,
  count: undefined,
  exchange: undefined,
  tax: undefined,
  productSaleUs: undefined,
  productSaleRmb: undefined,
  productPurhaseUs: undefined,
  productPurhaseRmb: undefined,
  otherSaleUs: undefined,
  otherSaleRmb: undefined,
  otherPurhaseUs: undefined,
  otherPurhaseRmb: undefined,
  discountSaleUs: undefined,
  discountSaleRmb: undefined,
  discountPurhaseUs: undefined,
  discountPurhaseRmb: undefined,
  totalSaleUs: undefined,
  totalSaleRmb: undefined,
  totalPurhaseUs: undefined,
  totalPurhaseRmb: undefined,
  productItems: undefined,
  otherItems: undefined,
})

const productItems = ref([])
const otherItems = ref([])

const formRules = reactive({
  no: [{required: true, message: t('su.invoice.no')+t('validate.notempty'), trigger: 'blur'}],
  customerId: [{required: true, message: t('su.invoice.customer')+t('validate.notempty'), trigger: 'blur'}],
  brandId: [{required: true, message: t('su.invoice.brand')+t('validate.notempty'), trigger: 'blur'}],
  supplierId: [{required: true, message: t('su.invoice.supplier')+t('validate.notempty'), trigger: 'blur'}],
  // productId: [{required: true, message: '商品不能为空', trigger: 'blur'}],
  // skuId: [{required: true, message: 'SKU不能为空', trigger: 'blur'}],
  // productSaleUs: [{required: true, message: 'productSaleUs不能为空', trigger: 'blur'}],
  // productPurhaseRmb: [{required: true, message: 'productPurhaseRmb不能为空', trigger: 'blur'}],
  // count: [{required: true, message: '数量不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref
const brandList = ref([])
const getBrandList = async () => {
  brandList.value = await CommonApi.getBrandList()
}

const customerList = ref([])
const getCustomerList = async () => {
  customerList.value = await CommonApi.getCustomerList()
}

const productList = ref([])
const getProductList = async () => {
  productList.value = await CommonApi.getProductList()
}

const companyList = ref([])
const getCompanyList = async () => {
  companyList.value = await CommonApi.getCompanyList()

  if (!formData.value.companyId) {
    const company = companyList.value.find((item) => item.defaultStatus)
    if (company) {
      formData.value.companyId = company.id
      chooseCompany()
    }
  }
}

const supplierList = ref([])
const getSupplierList = async () => {
  supplierList.value = await CommonApi.getSupplierList()

  if (!formData.value.supplierId) {
    const supplier = supplierList.value.find((item) => item.defaultStatus)
    if (supplier) {
      formData.value.supplierId = supplier.id
      chooseSupplier()
    }
  }
}

const companyBanks = ref([])
const chooseCompany = async () => {
  const queryParams = reactive({
    type: 'Company',
    compId: formData.value.companyId,
  })
  companyBanks.value = await CommonApi.getBankInfoList(queryParams)

  if (!formData.value.companyBankId) {
    const bank = companyBanks.value.find((item) => item.defaultStatus)
    if (bank) {
      formData.value.companyBankId = bank.id
    }
  }
}

const supplierBanks = ref([])
const chooseSupplier = async () => {
  const queryParams = reactive({
    type: 'Supplier',
    compId: formData.value.supplierId,
  })
  supplierBanks.value = await CommonApi.getBankInfoList(queryParams)

  if(!formData.value.supplierBankId) {
    const bank = supplierBanks.value.find((item) => item.defaultStatus)
    if (bank) {
      formData.value.supplierBankId = bank.id
    }
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  getBrandList()
  getCustomerList()
  getCompanyList()
  getSupplierList()
  getProductList()
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProformaInvoiceApi.getProformaInvoice(id)
      productItems.value = formData.value.productItems
      productItems.value.forEach(productItem => {
        changeProduct(productItem)
      })
      otherItems.value = formData.value.otherItems
    } finally {
      formLoading.value = false
    }
  } else {
    formData.value.exchange = 7
    formData.value.tax = 0.145
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  formData.value.productItems = productItems.value
  formData.value.otherItems = otherItems.value
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProformaInvoiceVO
    if (formType.value === 'create') {
      await ProformaInvoiceApi.createProformaInvoice(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProformaInvoiceApi.updateProformaInvoice(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const changeProduct = async (productItem) => {
  if (productItem && productItem.productId) {
    const params = {
      productId: productItem.productId,
    }
    productItem.skuInfos = await CommonApi.getProductSkuList(params);
  }
}

const changeSku = async (productItem) => {
  if (productItem && productItem.productId && productItem.skuId) {
    for (const item of productItem.skuInfos) {
      if (productItem.skuId == item.id) {
        productItem.productSaleUs = item.salePriceUs
        productItem.productPurhaseRmb = item.purchasePriceRmb
      }
    }
  }
}

const handleDelete = async (index) => {
  productItems.value.splice(index, 1);
}

const handleDeleteOther = async (index) => {
  otherItems.value.splice(index, 1);
}

const addProduct = async () => {
  const productItem = {
    id: undefined,
    piId: undefined,
    productId: undefined,
    productRefNo: undefined,
    productDes: undefined,
    skuInfos: [],
    skuId: undefined,
    skuDesc: undefined,
    brandId: undefined,
    supplierId: undefined,
    companyId: undefined,
    count: 1,
    exchange: undefined,
    productSaleUs: undefined,
    productSaleRmb: undefined,
    productPurhaseUs: undefined,
    productPurhaseRmb: undefined,
    totalSaleUs: undefined,
    totalSaleRmb: undefined,
    totalPurhaseUs: undefined,
    totalPurhaseRmb: undefined
  }
  productItems.value.push(productItem)
}

const addOther = async () => {
  const otherItem = {
    id: undefined,
    piId: undefined,
    brandId: undefined,
    supplierId: undefined,
    companyId: undefined,
    itemName: undefined,
    totalSaleUs: undefined,
    totalSaleRmb: undefined,
    totalPurhaseUs: undefined,
    totalPurhaseRmb: undefined,
    description: undefined
  }
  otherItems.value.push(otherItem)
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    no: undefined,
    invoiceDate: undefined,
    dueDate: undefined,
    kind: undefined,
    customerId: undefined,
    brandId: undefined,
    companyId: undefined,
    companyBankId: undefined,
    supplierId: undefined,
    supplierBankId: undefined,
    buyer: undefined,
    supplerManager: undefined,
    shipTo: undefined,
    po: undefined,
    notes: undefined,
    payAction: undefined,
    term: undefined,
    bill: undefined,
    remarks: undefined,
    count: undefined,
    productSaleUs: undefined,
    productSaleRmb: undefined,
    productPurhaseUs: undefined,
    productPurhaseRmb: undefined,
    otherSaleUs: undefined,
    otherSaleRmb: undefined,
    otherPurhaseUs: undefined,
    otherPurhaseRmb: undefined,
    discountSaleUs: undefined,
    discountSaleRmb: undefined,
    discountPurhaseUs: undefined,
    discountPurhaseRmb: undefined,
    totalSaleUs: undefined,
    totalSaleRmb: undefined,
    totalPurhaseUs: undefined,
    totalPurhaseRmb: undefined,
    productItems: undefined,
    otherItems: undefined,
  }
  productItems.value = []
  otherItems.value = []
  formRef.value?.resetFields()
}
</script>
